package com.bstek.pms.tools.utils;

import javafx.stage.DirectoryChooser;
import javafx.stage.Stage;
import org.springframework.util.StringUtils;

import java.io.File;

/**
 * @Description 文件操作工具类
 * @Author zhangkun
 * @CreateDate 2020/8/1
 */
public class FileUtils {

    /**
     * 删除目标目录下的文件
     * @param file
     */
    public static void deleteFiles(File file) throws Exception {
        try {
            if (file.exists()) {
                if (file.isDirectory()) {
                    File[] files = file.listFiles();
                    for (File file2 : files) {
                        deleteFiles(file2);
                    }
                }else if (file.isFile()) {
                    file.delete();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("清理文件夹出错：" + e.getMessage());
        }
    }


    /**
     * 选择文件输出路径
     * @return 目标文件夹目录
     */
    public static File chooseExportPath() {
        //输出文件到..
        DirectoryChooser directoryChooser = new DirectoryChooser();
        directoryChooser.setTitle("导出文件存放目录");
        Stage s = new Stage();
        return directoryChooser.showDialog(s);
    }

    /**
     * 文件选择弹框，并根据文件夹名创建文件夹
     * @return
     * @throws Exception
     */
    public static String generateExportDirs(String directoryName) throws Exception {
        //选择输出到的目标文件
        File chooseFile = FileUtils.chooseExportPath();
        String exportFilePath = chooseFile.getAbsolutePath();
        if(StringUtils.hasText(directoryName)){
            exportFilePath = chooseFile.getAbsolutePath() + File.separator + directoryName;
        }
        File exportFile = new File(exportFilePath);
        if(exportFile.exists()) FileUtils.deleteFiles(exportFile);
        exportFile.mkdirs();
        return exportFilePath;
    }


}
